package com.ejuornal.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ejuornal.bean.vo.Email;

public class EmailThread implements Runnable{
	private static final Logger logger = LoggerFactory.getLogger(EmailThread.class);
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public Email email;
	private static final String charset = "utf-8";
    private static final String defaultMimetype = "text/plain";
    
	public EmailThread(Email email) {
		this.email = email;
	}
	
	@Override
	public void run() {
		logger.info("发送邮件开始" + sdf.format(new Date()));
		Properties props = new Properties();
	    props.put("mail.smtp.host", "smtp.163.com");// Smtp服务器地址
	    props.put("mail.smtp.auth", "true");// 需要校验
	    Session session = Session.getDefaultInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("chenfeng_0829@163.com", "womenderizi");// 登录用户名/密码
            }
        });
	    session.setDebug(true);
	    MimeMessage mimeMessage = new MimeMessage(session);
        try {
			mimeMessage.setFrom(new InternetAddress("chenfeng_0829@163.com"));
			mimeMessage.setSubject(email.getSubject(), charset);
			
			InternetAddress[] ccs1 = new InternetAddress[email.getReceivers().length];
			for (int i = 0; i < email.getReceivers().length; i++) {
				ccs1[i] = new InternetAddress(email.getReceivers()[i]);
            }
			mimeMessage.setRecipients(Message.RecipientType.BCC, ccs1);
			mimeMessage.saveChanges();
	        Multipart multipart = new MimeMultipart();
	        MimeBodyPart body = new MimeBodyPart();
	        body.setContent(email.getMailContent(), (email.getMimetype() != null && !"".equals(email.getMimetype()) ? email.getMimetype() : defaultMimetype)
	                + ";charset=" + charset);
	        multipart.addBodyPart(body);
	        mimeMessage.setContent(multipart);
	        mimeMessage.setSentDate(new Date());
	        Transport.send(mimeMessage);
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 发件人邮件
        logger.info("发送邮件结束" + sdf.format(new Date()));
       
	}
	
	

}
